<template>
  <t-dialog
    :width="width ? width : '50%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    preventScrollThrough
    placement="center"
  >
    <template #header>{{ mode == "new" ? "新增" : mode == "edit" ? "编辑" : mode == "view" ? "查看" : "" }} </template>
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <t-form-item label="网站名称" name="name">
        <t-input v-model="pageData.formData.name" maxlength="50" />
      </t-form-item>
      <t-form-item label="网站地址" name="url">
        <t-input v-model="pageData.formData.url" maxlength="100" />
      </t-form-item>
      <t-form-item label="网站说明" name="remark">
        <t-input v-model="pageData.formData.remark" maxlength="100" />
      </t-form-item>
      <t-form-item label="创建人" name="createdByName">
        <t-input v-model="pageData.formData.createdByName" disabled />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import type { FormInstanceFunctions } from "tdesign-vue-next";

// 业务数据
import { useUserStore } from "@/stores/modules/user";

const props = defineProps(["width", "showDialog", "mode", "editFormData"]);
const emits = defineEmits(["onCancel", "onConfirm"]);

const userStore = useUserStore();
const formInstance = ref<FormInstanceFunctions | null>(null);

const pageData = reactive<Record<string, any>>({
  readOnly: false,
  formData: {
    id: "",
    createdTime: "",
    createdBy: "",
    status: 0,
    remark: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasDeleted: 0,
    name: "",
    url: "http://"
  },
  formRules: {
    name: [{ required: true, message: "名称必填", type: "error" }],
    url: [
      { required: true, message: "网店地址必填", type: "error" },
      { url: { protocols: ["http", "https"] }, message: "请输入正确的 url 地址" }
    ]
  }
});
const handleCancel = () => {
  emits("onCancel");
};

const handleConfirm = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    emits("onConfirm", toRaw(pageData.formData));
  }
};

if (props.editFormData) {
  pageData.formData = toRaw(props.editFormData);
}

if (props.mode === "new") {
  pageData.formData.createdBy = userStore.userData?.id;
  pageData.formData.createdByName = userStore.userData?.userName;
  pageData.formData.createdTime = new Date().toISOString();
}
</script>
